<?php

namespace app\admin\model\meet\product;

use app\admin\model\meet\Store;
use think\Model;
use traits\model\SoftDelete;

class Product extends Model
{

    use SoftDelete;


    // 表名
    protected $name = 'meet_product';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'spec_type_text',
        'status_text'
    ];


    protected static function init()
    {
        self::afterInsert(function ($row) {
            if (!$row['weigh']) {
                $pk = $row->getPk();
                $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
            }
        });

        self::beforeInsert(function ($row) {
            $row['store_id'] = Store::STORE_ID;
        });
    }

    public function category()
    {
        return $this->belongsTo('app\\admin\\model\\meet\\Category', 'category_id', 'id', '', 'LEFT')->setEagerlyType(0);
    }


    public function getSpecTypeList()
    {
        return ['10' => __('Spec_type 10'), '20' => __('Spec_type 20')];
    }

    public function getStatusList()
    {
        return ['hidden' => __('Hidden'), 'normal' => __('Normal')];
    }


    public function getSpecTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['spec_type']) ? $data['spec_type'] : '');
        $list = $this->getSpecTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 关联商品规格表
     */
    public function spec()
    {
        return $this->hasMany('Spec', 'product_id', 'id');
    }

    /**
     * 关联商品规格关系表
     */
    public function specRel()
    {
        return $this->belongsToMany('app\\admin\\model\\meet\\SpecValue', 'meet_product_spec_rel', 'spec_value_id', 'product_id');
    }

    /**
     * 添加产品规格
     * @param $data
     * @param $isUpdate
     * @throws \Exception
     */
    public function addProductSpec(&$data, $params, $specparams, $isUpdate = false)
    {
        // 更新模式: 先删除所有规格
        $model = new Spec();
        $isUpdate && $model->removeAll($this['id']);
        // 添加规格数据
        if ($data['spec_type'] === '10') {
            // 单规格
            $result = $this->spec()->save($specparams);

            if (!$result) {
                throw new \Exception(__('Operation failed'));
            }

        } else if ($data['spec_type'] === '20') {
            // 添加商品与规格关系记录
            $result = $model->addProductSpecRel($this['id'], $params['spec_attr']);
            // 添加商品sku
            $res = $model->addSkuList($this['id'], $params['spec_list']);

            if (!$result || !$res) {
                throw new \Exception(__('Operation failed'));
            }
        }
    }

    public function removesku()
    {
        // 删除商品sku
        (new Spec())->removeAll($this['id']);
    }

    /**
     * 获取规格信息
     */
    public function getManySpecData($spec_rel, $skuData)
    {
        // spec_attr
        $specAttrData = [];
        foreach ($spec_rel as $item) {
            if (!isset($specAttrData[$item['spec_id']])) {
                $specAttrData[$item['spec_id']] = [
                    'group_id' => $item['spec']['id'],
                    'group_name' => $item['spec']['spec_name'],
                    'spec_items' => [],
                ];
            }
            $specAttrData[$item['spec_id']]['spec_items'][] = [
                'item_id' => $item['pivot']['spec_value_id'],
                'spec_value' => $item['spec_value'],
            ];
        }

        // spec_list
        $specListData = [];
        foreach ($skuData as $item) {
            $specListData[] = [
                'product_spec_id' => $item['spec_id'],
                'spec_sku_id' => $item['spec_sku_id'],
                'rows' => [],
                'form' => [
                    'product_price' => $item['product_price'],
                    'product_deposit' => $item['product_deposit'],
                    'product_people_nums' => $item['product_people_nums'],
                    'spec_status' => $item['spec_status'],
                    'spec_image' => $item['spec_image'],
                ],
            ];
        }
        return ['spec_attr' => array_values($specAttrData), 'spec_list' => $specListData];
    }
}
